package com.myaihui.controller;

import com.myaihui.domain.Resource;
import com.myaihui.domain.Role;
import com.myaihui.domain.SysUser;
import com.myaihui.foundation.constant.SysConst;
import com.myaihui.foundation.model.Pager;
import com.myaihui.foundation.msg.MsgDefinition;
import com.myaihui.foundation.msg.ResultMsg;
import com.myaihui.foundation.query.UserQuery;
import com.myaihui.service.RoleService;
import com.myaihui.service.SysUserService;
import com.myaihui.util.EncryptUtil;
import com.myaihui.util.LoginUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by sun on 2018/7/3.
 *
 * @author sunfuchang03@126.com
 * @version 1.0
 * @since 1.0
 */
@RequestMapping("/users")
@Controller
public class UserController {
    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Static fields/constants/initializer
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    private static Logger log = LoggerFactory.getLogger(UserController.class);

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Instance fields
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RoleService roleService;

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Constructors
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */



    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Public Methods
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    @RequestMapping("/home")
    public String home(Model model) {
        return "user/home";
    }

    @RequestMapping("/add")
    public String add(Model model) {
        return "user/add";
    }

    @RequestMapping("/{userId}/edit")
    public String edit(@PathVariable("userId") String userId, Model model) {
        SysUser sysUser = sysUserService.getById(userId);
        model.addAttribute("user", sysUser);
        return "user/edit";
    }

    @PostMapping("/exists")
    @ResponseBody
    public ResultMsg checkNameExists(String userId, String name) {
        if (!StringUtils.hasLength(name)) {
            return ResultMsg.error(MsgDefinition.EMPTY_ARGUMENTS);
        }
        boolean exists = false;
        if (StringUtils.hasLength(userId)) {
            exists = sysUserService.findByUsernameExcludeId(name, userId) != null;
        } else {
            exists = sysUserService.findByUsername(name) != null;
        }
        return ResultMsg.success(exists);
    }

    @RequestMapping("/{userId}/roles")
    public String userRole(@PathVariable("userId") String userId, Model model) {
        SysUser sysUser = sysUserService.getById(userId);
        List<Role> roles = roleService.findByType(sysUser.getPlatformType());
        List<Role> userRoles = roleService.findByUserId(userId);
        for (Role role : roles) {
            for (Role userRole : userRoles) {
                if (userRole.getId().equals(role.getId())) {
                    role.setChecked(true);
                    break;
                }
            }
            List<Resource> resources = roleService.findResourcesByRoleId(role.getId());
            role.setResources(resources);
        }
        model.addAttribute("user", sysUser);
        model.addAttribute("roles", roles);
        return "user/role";
    }

    @RequestMapping("/{userId}/enable")
    @ResponseBody
    public ResultMsg enable(@PathVariable("userId") String userId) {
        SysUser sysUser = sysUserService.getById(userId);
        if (sysUser == null) {
            return ResultMsg.error(MsgDefinition.UNKOWN_ERROR, "用户不存在");
        }
        if (SysConst.UserState.ENABLE != sysUser.getState()) {
            sysUser.setState(SysConst.UserState.ENABLE);
            sysUserService.update(sysUser);
        }
        return ResultMsg.success(true);
    }

    @RequestMapping("/{userId}/disable")
    @ResponseBody
    public ResultMsg disable(@PathVariable("userId") String userId) {
        SysUser sysUser = sysUserService.getById(userId);
        if (sysUser == null) {
            return ResultMsg.error(MsgDefinition.UNKOWN_ERROR, "用户不存在");
        }
        if (SysConst.UserState.DISABLE != sysUser.getState()) {
            sysUser.setState(SysConst.UserState.DISABLE);
            sysUserService.update(sysUser);
        }
        return ResultMsg.success(true);
    }

    @RequestMapping("/page")
    @ResponseBody
    public ResultMsg pageQuery(UserQuery userQuery) {
        String platformId = LoginUtil.loginUser().getPlatformId();
        Integer platformType = LoginUtil.loginUser().getPlatformType();
        userQuery.setPlatformType(platformType == SysConst.SubjectType.SUPER_ADMIN ? SysConst.SubjectType.PLATFORM : platformType);
        userQuery.setPlatformId(platformId);
        Pager<SysUser> users = sysUserService.pageQuery(userQuery);
        return ResultMsg.success(users);
    }

    @RequestMapping("/{userId}/delete")
    @ResponseBody
    public ResultMsg delete(@PathVariable String userId) {
        SysUser sysUser = sysUserService.getById(userId);
        sysUser.setDeleted(true);
        sysUserService.update(sysUser);
        return ResultMsg.success(true);
    }

    @RequestMapping("/save")
    @ResponseBody
    public ResultMsg saveUser(SysUser sysUser) {
        String userId = sysUser.getId();
        SysUser loginUser = LoginUtil.loginUser();
        if (StringUtils.hasLength(userId)) {
            SysUser destUser = sysUserService.getById(userId);
            destUser.setRealName(sysUser.getRealName());
            destUser.setMobile(sysUser.getMobile());
            destUser.setGender(sysUser.getGender());
            sysUserService.update(destUser);
        } else {
            sysUser.setPassword(EncryptUtil.passwordEncrypt(sysUser.getUsername(), "123456"));
            sysUser.setCreated(new Date());
            sysUser.setCreateUserId(loginUser.getId());
            sysUser.setPlatformId(loginUser.getPlatformId());
            sysUser.setState(SysConst.UserState.ENABLE);
            sysUser.setPlatformType(
                    loginUser.getPlatformType() == SysConst.SubjectType.SUPER_ADMIN
                            ? SysConst.SubjectType.PLATFORM : loginUser.getPlatformType()
            );
            sysUserService.add(sysUser);
        }
        return ResultMsg.success(true);
    }

    @RequestMapping("/{userId}/role/save")
    @ResponseBody
    public ResultMsg saveRole(@PathVariable("userId") String userId, String roleIds) {
        if (!StringUtils.hasLength(roleIds)) {
            return ResultMsg.error(MsgDefinition.EMPTY_ARGUMENTS);
        }
        String[] roleIdsArray = roleIds.split(",");
        roleService.saveUserRoles(userId, Arrays.asList(roleIdsArray));
        return ResultMsg.success(true);
    }

    @RequestMapping(value = "/vPwd")
    @ResponseBody
    public ResultMsg validatePassword(String pwd) {
        if (!StringUtils.hasLength(pwd))
            return ResultMsg.success(false);
        String userId = LoginUtil.loginUser().getId();
        return ResultMsg.success(sysUserService.validatePassword(userId, pwd));
    }

    @RequestMapping(value = "/uPwd")
    @ResponseBody
    public ResultMsg updatePassword(String pwd) {
        if (!StringUtils.hasLength(pwd))
            return ResultMsg.success(false);
        try {
            String userId = LoginUtil.loginUser().getId();
            sysUserService.updatePassword(userId, pwd);
            return ResultMsg.success(true);
        } catch (Exception e) {
            log.error("get user : ", e);
            return ResultMsg.error(MsgDefinition.UNKOWN_ERROR.codeOf(), "密码修改失败，请稍后重试！");
        }
    }

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Private Methods
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */


}